package com.linxianqin.springbootVue.controller.system;

import com.linxianqin.springbootVue.config.SysBootVueConfig;
import com.linxianqin.springbootVue.domain.convert.SysDeptConvert;
import com.linxianqin.springbootVue.domain.dto.SysUserDTO;
import com.linxianqin.springbootVue.domain.entity.SysDept;
import com.linxianqin.springbootVue.domain.entity.SysUser;
import com.linxianqin.springbootVue.domain.enums.BusinessType;
import com.linxianqin.springbootVue.domain.model.AjaxResult;
import com.linxianqin.springbootVue.domain.model.LoginUser;
import com.linxianqin.springbootVue.manage.annotation.SysLog;
import com.linxianqin.springbootVue.manage.core.BaseController;
import com.linxianqin.springbootVue.service.SysDeptService;
import com.linxianqin.springbootVue.service.SysUserService;
import com.linxianqin.springbootVue.service.webService.TokenService;
import com.linxianqin.springbootVue.utils.SecurityUtils;
import com.linxianqin.springbootVue.utils.ServletUtils;
import com.linxianqin.springbootVue.utils.file.FileUploadUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * @author lxq
 * @version 1.0
 * @description: 个人信息 业务处理
 * @date 2020/12/18 11:55
 */
@RestController
@RequestMapping("/system/user/profile")
public class SysProfileController extends BaseController {
    private final SysUserService userService;
    private final TokenService tokenService;
    private final SysDeptService sysDeptService;
    public SysProfileController(SysUserService userService,TokenService tokenService,SysDeptService sysDeptService){
        this.userService=userService;
        this.tokenService=tokenService;
        this.sysDeptService=sysDeptService;
    }

    /**
     * 个人信息
     */
    @GetMapping
    public AjaxResult profile()
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        SysUserDTO userDTO = loginUser.getUser();
        AjaxResult ajax = AjaxResult.success(userDTO);
        userDTO.setDept(SysDeptConvert.INSTANCE.entity2dto(sysDeptService.getById(userDTO.getDeptId())));
        ajax.put("roleGroup", userService.selectUserRoleGroup(loginUser.getUsername()));
        ajax.put("postGroup", userService.selectUserPostGroup(loginUser.getUsername()));
        return ajax;
    }
    /**
     * 修改用户
     */
    @SysLog(title = "个人信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult updateProfile(@RequestBody SysUserDTO userDTO)
    {
        if (userService.updateUserProfile(userDTO) > 0)
        {
            LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
            // 更新缓存用户信息
            loginUser.getUser().setNickName(userDTO.getNickName());
            loginUser.getUser().setPhonenumber(userDTO.getPhonenumber());
            loginUser.getUser().setEmail(userDTO.getEmail());
            loginUser.getUser().setSex(userDTO.getSex());
            tokenService.setLoginUser(loginUser);
            return AjaxResult.success();
        }
        return AjaxResult.error("修改个人信息异常，请联系管理员");
    }

    /**
     * 重置密码
     */
    @SysLog(title = "个人信息", businessType = BusinessType.UPDATE)
    @PutMapping("/updatePwd")
    public AjaxResult updatePwd(String oldPassword, String newPassword)
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        String userName = loginUser.getUsername();
        String password = loginUser.getPassword();
        if (!SecurityUtils.matchesPassword(oldPassword, password))
        {
            return AjaxResult.error("修改密码失败，旧密码错误");
        }
        if (SecurityUtils.matchesPassword(newPassword, password))
        {
            return AjaxResult.error("新密码不能与旧密码相同");
        }
        if (userService.resetUserPwd(userName, SecurityUtils.encryptPassword(newPassword)) > 0)
        {
            // 更新缓存用户密码
            loginUser.getUser().setPassword(SecurityUtils.encryptPassword(newPassword));
            tokenService.setLoginUser(loginUser);
            return AjaxResult.success();
        }
        return AjaxResult.error("修改密码异常，请联系管理员");
    }

    /**
     * 头像上传
     */
    @SysLog(title = "用户头像", businessType = BusinessType.UPDATE)
    @PostMapping("/avatar")
    public AjaxResult avatar(@RequestParam("avatarfile") MultipartFile file) throws IOException
    {
        if (!file.isEmpty())
        {
            LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
            String avatar = FileUploadUtils.upload(SysBootVueConfig.getAvatarPath(), file);
            if (userService.updateUserAvatar(loginUser.getUsername(), avatar))
            {
                AjaxResult ajax = AjaxResult.success();
                ajax.put("imgUrl", avatar);
                // 更新缓存用户头像
                loginUser.getUser().setAvatar(avatar);
                tokenService.setLoginUser(loginUser);
                return ajax;
            }
        }
        return AjaxResult.error("上传头像异常，请联系管理员");
    }
}
